package com.hugang.juc.security;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 模拟卖票： 三个售票员 卖出 30 张票
 * 多线程编程的模板： 在高内聚低耦合的前提下，线程  操作（对外暴露的方法）  资源类
 *
 * @author hg
 * @date 2020/8/2 19:08
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(() -> {
            while (true) {
                ticket.saleTicket();
            }
        }, "线程1");
        Thread t2 = new Thread(() -> {
            while (true) {
                ticket.saleTicket();
            }
        }, "线程2");
        t1.start();
        t2.start();


    }

    /**
     * 资源类
     */
    static class Ticket {
        /**
         * 可重入锁
         */
        private final Lock lock = new ReentrantLock();
        private int num = 30;

        public void saleTicket() {
            lock.lock();
            try {
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + "线程买到第" + num-- + "张票");
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
